let { HttpRequest, globalData, cloud, CloudFunction, UserAccess, addUserStat, mfutil, URLChangeCommon } = getApp();

const app = getApp();



Page({

  data: {

    integralquestion: false,   //问卷弹窗展示状态

    active: false,   //待完成true,已完成false,废弃

    id: null,

    json: '',

    submitData: {},   //问卷提交所需title数据,

    item: '',

    type: '',  //自拍或者相机

    ugc_type: '',

    currentImg: '',

    currentList: [],

    nextActive: false,

    popActive: false,

    successActive: false,

    loadingActiveup: false,

    radioActive: false,

    hyperlinkAcitve: false,

    router: '/pages/getIntegral-detail/getIntegral-detail',

    pagetitle: '赚积分详情页',

    illegal: false,

    scrolly: true,

    scrollTop: 0,

    loadingActive: false,
    newState: null,
    flag: false
  },

  onLoad(options) {
    console.log(321321312);


    this.videoContext = my.createVideoContext('myVideo');


    my.hideShareMenu({

      success() {

      },

      fail() {

      },

    });

    let a = getCurrentPages();

    let { activetype, id } = options;

    this.setData({

      activetype,

      id

    })
    console.log(id);


    // my.alert({

    //   content:`id----${id}`

    // })

    this.setData({

      loadingActive: true

    })

    this.initPage();

    this.setData({

      loadingActive: false

    })

    /**

* 用户行为记录埋点

*/

    let routerArr = getCurrentPages();

    let params = app.globalData.params;

    let channel = app.globalData.channel;

    let UserAccessoptions = {

      grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',

      name: routerArr[routerArr.length - 1].data.pagetitle,

      address: routerArr[routerArr.length - 1].data.router,

      String4: params ? `params=${params.join(',')}&` : '' + `tileid=${id}${channel ? '&channel=' + channel : ''}`

    }

    let track = UserAccess(UserAccessoptions)


    // 自定义埋点
    let customAccessoptions = {
      customType: 'TileCover_' + id,
      // tileId: id
    }
    console.log(id, '进入Tile封面');

    let tracks = addUserStat(customAccessoptions)



  },
  onHide(){
    this.setData({

    })
  },

  /**

   * 初始化数据

   * @param {*} options 

   */

  async initPage() {

    let { id, submitData } = this.data;

    let parmasObj = {

      member_id: globalData.userInfo.memberId,

      member_id_type: 1,

    }

    let path = `/vans-family/api/v2.1/project/vansFamily/cms/forward/get?url=/v2/cms/api/tile/${id}`;



    let res = await HttpRequest(path, 'POST', parmasObj, {});

    submitData = {

      type: res.data.data.tile_info.type,

      id: res.data.data.tile_info.id,

    }

    if (res.data.code == 0) {

      let json = res.data.data

      this.setData({

        json,

        submitData,

        // ugc_type: res.data.data.tile_info.ugc_type ? res.data.data.tile_info.ugc_type : '',
        ugc: res.data.data.tile_info.ugc ? res.data.data.tile_info.ugc : '',
        time: res.data.data.tile_info.required_duration ? res.data.data.tile_info.required_duration : ''

      })

      console.log(json)

    }



  },

  questionNavChange() {

    let { integralquestion } = this.data;

    this.setData({

      integralquestion: !integralquestion

    })

  },

  getIntegral2() {

    let { json, id, ugc } = this.data;
    // console.log(ugc);
    // console.log(json.tile_info.ugc);
    
    

    // let event = { currentTarget: { dataset: { type: 'camera', item: '' } } }

    // if (ugc_type == 'video') {

    //   event.currentTarget.dataset.item = 'video';

    //   this.videoFn(event)

    // } else {

    //   event.currentTarget.dataset.item = 'camera';

    //   this.cameraFn(event)

    // }
    console.log(json.tile_info ,id );
    
    my.redirectTo({

      url: `/pages/showUGCList/showUGCList?ugc_type=${JSON.stringify(json.tile_info)}`

    });

  },

  // 相机
  cameraFn(event) {

    let { item, type } = event.currentTarget.dataset;

    this.setData({

      item,

      type

    })

    this.chooseImage(type)

  },

  // 选择照片

  albumFn(event) {

    let { item, type } = event.currentTarget.dataset;

    this.setData({

      item,

      type

    })

    this.chooseImage(type)

  },

  chooseImage(event) {

    my.chooseImage({

      count: 1,

      sourceType: ['camera', 'album'],

      isClipped: false, //防止对图片进行剪裁

      success: async (chooseImageres) => {

        // 获取图片大小，最大限制为10MB

        my.getFileInfo({

          apFilePath: chooseImageres.apFilePaths[0],

          digestAlgorithm: 'sha1',

          success: (getFileInfores) => {

            if (getFileInfores.size > 10485760) {

              my.alert({

                content: '请上传10MB以内的图片资源！'

              })

              return

            }

            this.setData({

              videoBtn: 1,

              loadingActive: true

            })

            let fileType = /\.[^\.]+$/.exec(chooseImageres.apFilePaths[0]);

            cloud.file.uploadFile({

              filePath: chooseImageres.apFilePaths[0],

              fileType: 'image',

              fileName: `/miniapp_res/icon_${new Date().getTime()}${fileType}`,

              success: async (uploadFileres) => {

                //检测图片

                my.tb.imgRisk({

                  data: {

                    cloudFileId: uploadFileres.fileId

                  },

                  success(imgRiskres) {

                    imgRiskres.data.result.checkPoints.forEach((value, index) => {

                      if (value.label != 'normal') {

                        my.alert({

                          content: '您上传的内容未通过审核，请更换其他内容'

                        })

                        this.setData({

                          illegal: true

                        })

                        return

                      }

                    })

                  },

                  fail() {
                    // debugger

                    my.alert({ title: '检查失败' });

                  },

                })

                if (this.data.illegal) {

                  return

                }

                let { currentList } = this.data;

                currentList[0] = uploadFileres.url

                this.setData({

                  fileId: uploadFileres.fileId,

                  currentImg: uploadFileres.url,

                  currentList,

                  loadingActive: false

                })

              },

              error: (err) => {

                this.setData({

                  videoBtn: 0

                })

                my.showToast({

                  type: "fail",

                  content: "图片上传失败" + JSON.string(err)

                });

              }

            })

          }

        })

      },

      fail: (error) => {

        this.setData({

          videoBtn: 0

        })

        console.log(error, 'fail')

      }

    });

  },



  //视频部分

  videoFn(event) {

    let { item, type } = event.currentTarget.dataset;

    this.setData({

      item,

      type

    })

    this.chooseVideo(type)

  },

  videoAlbumFn(event) {

    let { item, type } = event.currentTarget.dataset;

    this.setData({

      item,

      type

    })

    this.chooseVideo(type)

  },

  chooseVideo(event) {

    my.chooseVideo({

      sourceType: ['camera', 'album'],

      maxDuration: 60,

      camera: 'back',

      success: async (chooseVideores) => {

        //获取视频大小，最大限制为10MB

        my.getFileInfo({

          apFilePath: chooseVideores.apFilePath,

          digestAlgorithm: 'sha1',

          success: (getFileInfores) => {

            if (getFileInfores.size > 20971520) {

              my.alert({

                content: '请上传20MB以内的视频资源！'

              })

              return

            }

            this.setData({

              videoBtn: 1,

              loadingActiveup: true

            })

            let filetype = /\.[^\.]+$/.exec(chooseVideores.apFilePath);

            cloud.file.uploadFile({

              filePath: chooseVideores.apFilePath,

              fileType: 'video',

              fileName: `/miniapp_video/video_${new Date().getTime()}${filetype}`,

              success: async (uploadFileres) => {

                let url = uploadFileres.url;

                setInterval(async () => {

                  if (!url) {

                    let urls = await cloud.file.getTempFileURL({

                      fileId: [uploadFileres.fileId]

                    })

                    url = urls[0].url

                    if (url) {

                      let { currentList } = this.data;

                      currentList[0] = url

                      this.setData({

                        fileId: uploadFileres.fileId,

                        currentImg: url,

                        currentList,

                        loadingActiveup: false

                      })

                    }

                  }

                }, 2000);

              },

              error: (err) => {

                this.setData({

                  videoBtn: 0

                })

                my.showToast({

                  type: "fail",

                  content: "视频上传失败" + JSON.string(err)

                });

              }

            })

          },

          fail: (error) => {

            console.log(error, '000000000000000000000')

          }

        })

      },

      fail: (err) => {

        if (err.error == -1) {

          my.showToast({

            type: 'fail',

            content: '请上传60s以内的视频!',

            duration: 1500,

          });

        }

        my.hideLoading({

          page: this,  // 防止执行时已经切换到其它页面，page指向不准确

        });

        this.setData({

          videoBtn: 0

        })

      }

    })

  },

  /**

   * 重新拍摄照片

   */

  anewCamera() {

    let { currentList, type } = this.data;

    currentList.pop();

    this.setData({

      currentImg: '',

      currentList,

      videoBtn: 0

    })

    this.chooseImage(type)

  },

  /**

   * 重新拍摄视频

   */

  anewVideo() {

    let { currentList, type } = this.data;

    currentList.pop();

    this.setData({

      currentImg: '',

      currentList,

      videoBtn: 0

    })

    this.chooseVideo(type)

  },

  /**

   * 下一步

   */

  nextStep() {

    this.setData({

      nextActive: true

    })

  },

  /**

   * 删除图片

   */

  delectImg(event) {

    let { index } = event.currentTarget.dataset;

    let { currentList, type, item } = this.data;

    // if (item == 'camera') {

    //   this.anewCamera()

    // } else {

    //   this.anewVideo()

    // }

    currentList.splice(index, 1);

    this.setData({

      currentList

    })

  },

  /**

  * 取消

  */

  exit() {

    this.setData({

      popActive: true

    })

  },

  /**

   * 继续编辑

   */

  nextEdit() {

    console.log('继续编辑')

    this.setData({

      popActive: false

    })

  },
  // 视频开始播放
  videoPlay() {
    console.log("视频开始播放");

  },

  /**

   * 视频结束弹窗

   */

  videoEnd() {

    let { successActive } = this.data;

    this.setData({

      successActive: !successActive

    })

  },

  /**

   * 确认离开

   */

  subExit() {

    this.setData({

      nextActive: false,

      popActive: false,

      currentList: [],

      currentImg: ''

    })

  },

  //确认提交

  async submitFn() {
    // debugger
    console.log(this.data.item);


    let { currentList, id, currentImg, fileId } = this.data;

    //上传

    let path = `/vans-family/api/v2.1/project/vansFamily/cms/upload`;

    let parmasObj = {

    }

    let bodyObj = {

      "fileUrl": currentImg,

      "tile_id": id,

      "member_id": globalData.userInfo.memberId

    }

    this.setData({
      loadingActive: true
    })
    let result = await HttpRequest(path, 'POST', parmasObj, bodyObj)
    this.setData({
      loadingActive: false
    })
    if (result.data.code == 0) {
      // 完成任务
      let time = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " ").replace(/\-/g, "/");
      let { json } = this.data;
      let bodyObj1 = {
        do_datetime: time,
        ugc_media_list: [result.data.data.url]
      }
      json.related.info.ugc_media_list.push(result.data.data.url)
      let parmasObj1 = {
        member_id_type: 1,
        member_id: globalData.userInfo.memberId
      }
      if (!this.data.flag) {
        this.data.flag = true
        let path1 = `/vans-family/api/v2.1/project/vansFamily/cms/forward/post?url=/v1/cms/api/tile/${json.tile_info.type}/${json.tile_info.id}/done`;
        let res = await HttpRequest(path1, 'POST', parmasObj1, bodyObj1);
        this.data.flag = false
        if (res.data.code == 0) { 

          // debugger
          this.setData({
            successActive: true,
            currentImg: ''
          })
          let ret = await cloud.file.deleteFile({
            fileId: fileId
          });
        } else if (res.data.code == 53012 || res.data.code == 53014 || res.data.code == 53001) {
          //  console.log('3333333333333333333333333333');
          my.alert({
            content: res.data.msg
          })
        } else {
          // console.log('4444444444444444444444444444444444' );

          mfutil.launchErrPage(53001)
        }
        // 自定义埋点
        let customAccessoptions = {
          customType: 'TileDone_' + id+'_上传完成TileDone',
          // tileId: id,
          // points: json.tile_info.points
        }
        console.log(id, 'TileDone');

        let tracks = addUserStat(customAccessoptions)


      } else {
        my.alert({
          content: result.data.msg
        })
        // mfutil.launchErrPage(53001)
      }

    }
    else {
      // debugger
      my.alert({
        content: result.data.msg
      })
    }

    /**

    * 用户行为记录埋点

    */

    let routerArr = getCurrentPages();

    let options = {

      grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',

      name: routerArr[routerArr.length - 1].data.pagetitle,

      address: routerArr[routerArr.length - 1].data.router,

      String4: ''

    }

    let track = UserAccess(options)

  },

  urlChange(event) {
    // debugger
    console.log('-----------------------------', '11');

    let { item } = event.currentTarget.dataset;

    URLChangeCommon(item)

    // 自定义埋点
    let customAccessoptions = {
      customType: 'TileCTA_' + this.data.json.tile_info.id + '_' + item.cta_button_name,
      // tileId: this.data.json.tile_info.id,
      // ctabtn: this.data.json.tile_info.cta_button_name
    }

    let tracks = addUserStat(customAccessoptions)

  },

  shareFn() {
    my.showSharePanel();

  },

  //单选协议同意/默认

  radioChange() {

    let { radioActive } = this.data;

    this.setData({

      radioActive: !radioActive

    })

  },

  /**

 * 链接文字点击

 */

  hyperlinkChange() {

    let { hyperlinkAcitve } = this.data;

    this.setData({

      hyperlinkAcitve: !hyperlinkAcitve

    })

  },

  //视频播放
  saveRef(ref) {
    this.videModal = ref

  },
  playVideo() {
    this.videModal.play()
  },
  onScroll(event) {

    this.setData({

      scrollTop: event.detail.scrollTop,

      ScrollToUpper: scrollTop == 0 ? true : false

    })

    if (scrollTop == 0) {

      this.setData({

        ScrollToUpper: true

      })

    }

  },

  onTouchStart(event) {

    console.log(event, 'onTouchStartonTouchStart')

    this.setData({

      starty: event.changedTouches[0].pageY,

    })

  },

  onTouchMove(event) {

    //当前pagey

    this.setData({

      movey: event.changedTouches[0].pageY

    })

    let { scrollTop } = this.data;

    let { ScrollToUpper, ScrollToLower, movey, starty } = this.data;

    if (ScrollToUpper && (starty > movey)) {

      this.setData({

        scrolly: true,

        ScrollToUpper: false,

        ScrollToLower: false

      })

    } else

      if (ScrollToUpper && (starty < movey)) {

        this.setData({

          scrolly: false,

        })

      }

    if (ScrollToLower && (starty < movey)) {

      this.setData({

        scrolly: true,

        ScrollToUpper: false,

        ScrollToLower: false

      })

    } else

      if (ScrollToLower && (starty > movey)) {

        this.setData({

          scrolly: false,

        })

      }

  },

  onScrollToUpper(event) {

    this.setData({

      scrolly: false,

      ScrollToUpper: true,

      ScrollToLower: false

    })

  },

  onScrollToLower() {

    this.setData({

      scrolly: false,

      ScrollToLower: true,

      ScrollToUpper: false

    })

  }

});












